package com.fsd.admin.shiro.realm;

import javax.annotation.Resource;

import com.fsd.admin.service.Sys_SystemParametersService;
import com.fsd.core.util.LDAPAuthentication;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import com.google.code.kaptcha.Constants;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.core.bean.shiro.CaptchaException;
import com.fsd.core.bean.shiro.UsernamePasswordCaptchaToken;
import com.fsd.core.util.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用户和权限的认证
 */
public class ShiroRealm extends AuthorizingRealm{
	
	@Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService a_EmployeeService;

	@Autowired
	private Sys_SystemParametersService systemParametersService;
	
	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException{

		UsernamePasswordCaptchaToken token = (UsernamePasswordCaptchaToken) authcToken;
		
		// 增加判断验证码逻辑
		String captcha = token.getCaptcha();
		String exitCode = SecurityUtils.getSubject().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
		if(captcha == null || !captcha.equals(exitCode)){
			throw new CaptchaException("captcha error.");
		}
		
		String username = token.getUsername();
		A_Employee user = a_EmployeeService.getObjectByUsername(username);
		
		if(user == null){
			// 没找到帐号
			throw new UnknownAccountException("Null usernames are not allowed by this realm.");
		}
		if(!"ryztqy".equals(user.getStatus())){
			// 帐号锁定
			throw new LockedAccountException("Accounts are locked");
		}

		String isauth = systemParametersService.getParameterValueByCodeSql("FSDISAUTH");
		if(isauth != null && "true".equals(isauth)){
			if(!"admin".equals(username) && !user.getUsertypeid().equals("zj")){
				try{
					LDAPAuthentication ldap = new LDAPAuthentication();
					ldap.LDAP_connect();
					if(!ldap.authenricate(username, token.getLdappassword())){
						throw new IncorrectCredentialsException();
					}
				}catch (Exception e){
					throw new IncorrectCredentialsException();
				}
			}
		}

		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
			// 用户名
			user.getLoginname(),
			// 密码
			user.getPassword(),
			// salt = Username + Salt (这里将用户的 登陆账号作为其加密的盐值)
			ByteSource.Util.bytes(token.getStrpassword()),
			// realm name
			getName()
		);
		return authenticationInfo;
	}
	
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String currentUsername = (String)super.getAvailablePrincipal(principals);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return null;
	}
	
	/**
	 * 更新用户授权信息缓存.
	 */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }
    
    public static void main(String[] args) {
    	System.out.println(EncryptUtils.md5Password("111", "111"));
	}
}
